/**
 * FormChoice.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormChoice.java
 *
 * Created on 05/04/2009, 20:33:16
 */

package trabpoo;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import plagio.postgres.ConnectionPostgres;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import plagio.utils.ArffGenerate;

/**
 *
 * @author jmsandy
 */
public class FormChoice extends javax.swing.JDialog {

    private ConnectionPostgres conn;
    private String query;
    private ResultSet result;
    private String file = "";
    private String text = "";

    /**
     * @return the text
     */
    public String getText() {
        return text;
    }
    /**
     * @return the file
     */
    public String getFile() {
        return file;
    }
    /** Creates new form FormChoice */
    public FormChoice() {
        initComponents();

        tableResult.getColumnModel().getColumn(0).setPreferredWidth(50);
        tableResult.getColumnModel().getColumn(0).setResizable(false);
        tableResult.getColumnModel().getColumn(1).setPreferredWidth(452);
        tableResult.getColumnModel().getColumn(1).setResizable(false);
        tableResult.getTableHeader().setReorderingAllowed(false);
        tableResult.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tableResult.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        try{
            Properties props = System.getProperties();
            props.load(ClassLoader.getSystemResourceAsStream("plagio.properties"));
            conn = new ConnectionPostgres();
            if(conn.connection(props.getProperty("user"),
                props.getProperty("password"),props.getProperty("url"))){
                // Inserting the file imported.
                Statement stat;
                stat = conn.getConnection().createStatement
                     (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                query = "SELECT * FROM \"FileImport\"";
                result = stat.executeQuery(query);
                showResult();
            }
        }catch(Exception e){
            System.out.print(e.getMessage() + " ");
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tableResult = new javax.swing.JTable();
        textFile = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Select the File");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        tableResult.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Code", "File"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableResult.setAutoscrolls(false);
        tableResult.setRowHeight(26);
        jScrollPane1.setViewportView(tableResult);

        textFile.setFont(new java.awt.Font("SansSerif", 0, 12));
        textFile.setToolTipText("Name file");
        textFile.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                textFileKeyReleased(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("SansSerif", 1, 14));
        jLabel1.setText("File");

        jButton1.setFont(new java.awt.Font("SansSerif", 1, 14));
        jButton1.setText("OK");
        jButton1.setToolTipText("Select File");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(textFile, javax.swing.GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 521, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(237, 237, 237)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textFile, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-555)/2, (screenSize.height-314)/2, 555, 314);
    }// </editor-fold>//GEN-END:initComponents

    private void textFileKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFileKeyReleased
        // TODO add your handling code here:
        Statement stat;
        try {
            result.close();
            stat = conn.getConnection().createStatement
                 (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            query = "SELECT * FROM \"FileImport\" WHERE title like \'" ;
            query += textFile.getText().toString().toUpperCase() + "%\'";
            result = stat.executeQuery(query);
            showResult();
        } catch (SQLException ex) {
            System.out.print(ex.getMessage());
        }
    }//GEN-LAST:event_textFileKeyReleased

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
        conn.closeConnection();
        this.setVisible(false);
    }//GEN-LAST:event_formWindowClosed

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        // TODO add your handling code here:
        try{
            // Checks if was selected any record.
            if(tableResult.getSelectedRow() > -1){
                this.file = tableResult.getValueAt(
                        tableResult.getSelectedRow(), 0)
                 + " - " + tableResult.getValueAt(
                        tableResult.getSelectedRow(), 1);

                result.absolute(tableResult.getSelectedRow() + 1);
                this.text = result.getString(7);
            }
            else this.file = "";
        }catch(Exception e){
            System.out.print(e.getMessage());
        }
        finally{
            conn.closeConnection();
            this.setVisible(false);
        }
    }//GEN-LAST:event_jButton1MouseClicked

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormChoice().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tableResult;
    private javax.swing.JTextField textFile;
    // End of variables declaration//GEN-END:variables

    private void showResult(){
        DefaultTableModel def = (DefaultTableModel)tableResult.getModel();
        def.getDataVector().clear();
        tableResult.updateUI();
        try {
            while(result.next()){
                Object[] row = new Object[]{result.getString(1),
                result.getString(2)};
                def.addRow(row);
//                ch(result.getString(7).split("\n"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(FormChoice.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void ch(String[] s){
        try {
            java.io.FileWriter f = new java.io.FileWriter("teste1.arff");
            ArffGenerate arf = new ArffGenerate();
//            f.append(arf.fileArff(s, "teste", 1));
            f.flush();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}